package org.shangrila.bme.mb;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.enterprise.context.SessionScoped;
import javax.faces.model.SelectItem;
import javax.inject.Inject;
import javax.inject.Named;

import org.primefaces.event.RowEditEvent;
import org.shangrila.app.sys.cfg.AppInitInfo;
import org.shangrila.app.sys.shiro.SecUtil;
import org.shangrila.bme.eo.AppFileInfo;
import org.shangrila.bme.eo.BmeAcception;
import org.shangrila.bme.eo.BmeAcceptionDetail;
import org.shangrila.bme.eo.BmeContract;
import org.shangrila.bme.eo.BmePayroll;
import org.shangrila.bme.eo.BmePayrollDetail;
import org.shangrila.comm.dao.DbAccess;
import org.shangrila.comm.helper.IDHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Named
@SessionScoped
public class PayrollMB implements Serializable {
	private static final long serialVersionUID = -513126664217112L;
	private final Logger log = LoggerFactory.getLogger(this.getClass());

    private BmePayroll io = new BmePayroll();//录入    

	private List<BmePayrollDetail> vod = new ArrayList<BmePayrollDetail>(); //详情
	private BmePayrollDetail selectedd = new BmePayrollDetail();//录入以及选择详情信息	

	private List<BmeContract> bmeContracts; 	
	private BmeContract selectedContract = new BmeContract(); 

	private List<BmeAcceptionDetail> bmeAcceptionDetails = new ArrayList<BmeAcceptionDetail>(); 
	private BmeAcceptionDetail selectedAcceptionDetail = new BmeAcceptionDetail(); 
	private List<BmeAcceptionDetail> selectedAcceptionDetails = new ArrayList<BmeAcceptionDetail>();

	//获取相关数据字典
	private List<SelectItem> itemsStatus = AppInitInfo.getDropdownList("PayrollStatus"); 

	private String operator;	
	private String uploadedFile="";
	private String uploadedFileImage="";

	//附件上传页面参数传递
	private String uploadForType="6";
	private String uploadForId="0";
	private String uploadForName="0";

	@Inject
	private DbAccess db;
	@Inject
	BmeCommEntityService bmeCommEntityService; 
	@Inject
	private AttachUploadMB attachUploadMB;
	
	@PostConstruct
    public void init() {
		log.info("@PostConstruct..."+this.getClass());

		try{
			operator = SecUtil.getCachedShiroUser().getUserno();
		}
		catch(Exception ex){
			operator="bme";
		}
		initdata();
		newIo();
    }

	public void initdata() {
    	bmeContracts = bmeCommEntityService.getBmeContracts();
    	/*
    	selectedContract = bmeContracts.get(0);

		if(null!=selectedContract) {
	    	for(BmeAcception bsd:selectedContract.getBmeAcceptions()) {
	    		bmeAcceptionDetails.addAll(bsd.getBmeAcceptionDetails());
	    	}
		}
		*/
	}
    public void newIo() {
    	initdata();
    	io = new BmePayroll();
    	io.setId(IDHelper.genStrID(20));
    	io.setStatus("1");
    	io.setCreateTime(new Date());
    	vod = new ArrayList<BmePayrollDetail>();
    	attachUploadMB.setVoList(new ArrayList<AppFileInfo>());
    	attachUploadMB.setUploadedFileImage("");
    }    

	//null
	public String nullAction() {
		if(!validDetailAction()) {
			return null;
		}
		
		//判断请款单的物料所属的验收单是否完成
		List<Object> params = new ArrayList<>();
		StringBuilder acpSql=
				new StringBuilder("SELECT s FROM BmeAcceptionDetail s WHERE s.bmeAcception.id=");
		StringBuilder pdSql=
				new StringBuilder("SELECT s FROM BmePayrollDetail s WHERE s.bmeAcception.id=");
		
		for (BmePayrollDetail detail : vod) {
			BmeAcception acception = detail.getBmeAcception();
			acpSql=acpSql.append("'"+acception.getId()+"'");
			pdSql=pdSql.append("'"+acception.getId()+"'");
			/*params.add(0,acception);*/
			//获取该验收单详情的物料金额总和
			List<BmeAcceptionDetail> acpts=db.findBySql(acpSql.toString());
			BigDecimal acptsum=new BigDecimal("0");
			for (BmeAcceptionDetail acpt : acpts) {
				acptsum=acptsum.add(acpt.getAmount());
			}
			//获取该验收单在请款单详情中的请款总额
			List<BmePayrollDetail> pds=db.findBySql(pdSql.toString());
			BigDecimal dpsum=new BigDecimal("0");
			for (BmePayrollDetail dp : pds) {
				dpsum=dpsum.add(dp.getAmount());
			}
			
			if (acptsum.compareTo(dpsum)!=1) {
				acception.setStatus("0");
				db.beginTransaction();
				db.update(acception);
				db.commitTransaction();
			}
			
		}
		AppInitInfo.showMessage("提交处理", "成功");
		return null;
	}
    
	//新增
    public void onAdd() {   
    	newIo();
    	AppInitInfo.showMessage("新增请款单", "处理成功");
    }
    //保存
	public String saveAction() {		
		db.beginTransaction();
		io.setBmeContract(selectedContract);
		io.setContName(selectedContract.getName());
		io.setOperator(operator);
		db.insert(io);
		db.commitTransaction();
		AppInitInfo.showMessage("单据录入", "处理成功");
		uploadForId=io.getId();
		uploadForName=io.getContName();
		
		//判断验收单是否完成，并改验收单的状态为‘0’
		
		return null;
	}
	//选择合同
	public void onSelectedContract() {
		if(null!=selectedContract) {
			bmeAcceptionDetails = new ArrayList<BmeAcceptionDetail>();
	    	for(BmeAcception bsd:selectedContract.getBmeAcceptions()) {
	    		bmeAcceptionDetails.addAll(bsd.getBmeAcceptionDetails());
	    	}
		}
	}
	//验证详单操作的有效性
	public boolean validDetailAction(){
		if(null==io.getCreateTime()) {
			AppInitInfo.showMessage("warn","操作无效", "请确保单据主体信息已经保存");
			return false;
		}
		else
			return true;
	}	

    //保存
	public String saveDetail() {	
		if(!validDetailAction()) {
			return null;
		}
		List<BmePayrollDetail> bpdList = new ArrayList<BmePayrollDetail>();
		for(BmeAcceptionDetail bsd:selectedAcceptionDetails) {
			selectedd = new BmePayrollDetail();
			selectedd.setId(IDHelper.genStrID(20));
			selectedd.setBmeMaterial(bsd.getBmeMaterial());
	     	selectedd.setBmeAcception(bsd.getBmeAcception());
	     	selectedd.setMdesc(bsd.getBmeMaterial().getMdesc());
	     	selectedd.setQtyAccept(bsd.getMquantity());
	     	selectedd.setQty(bsd.getMquantity());
	     	selectedd.setMprice(bsd.getMprice());
	     	selectedd.setAmount(bsd.getAmount());
	     	selectedd.setBmePayroll(io);
			selectedd.setCreateTime(new Date());
			selectedd.setOperator(operator);
			bpdList.add(selectedd);
		}    
		try {	
			db.beginTransaction();
	    	io.setAmount(calculateAmount());
			for(BmePayrollDetail bcp:bpdList) {
				db.insert(bcp);
			}
			db.update(io);
			db.commitTransaction();
			vod.addAll(bpdList);
			io.setBmePayrollDetails(vod);
			AppInitInfo.showMessage("info","新增详情录入", "处理成功");
			selectedAcceptionDetails=null;
		}catch(Exception e) {			
			AppInitInfo.showMessage("error","新增详情失败", "请确保单据主体信息已经保存");
			log.error(e.getLocalizedMessage());
			try {
				db.rollbackTransaction();
			}catch(Exception ex) {	}
		}		
		return null;		
	}
	//删除
    public String delDetail() {
    	vod.remove(selectedd);
    	io.setAmount(calculateAmount());
		db.beginTransaction();
		db.update(io);
		db.delete(selectedd);
		db.commitTransaction();
		
        AppInitInfo.showMessage("删除记录", "处理成功");
        return null;
    }
	
	//编辑
    public void onRowEdit(RowEditEvent event) {
    	selectedd = vod.get(vod.indexOf((BmePayrollDetail) event.getObject()));
     	selectedd.setAmount( (null==selectedd.getMprice() ? new BigDecimal(0) : selectedd.getMprice()).multiply((null==selectedd.getQty() ? new BigDecimal(0) : selectedd.getQty())) );  	
    	io.setAmount(calculateAmount());
    	db.beginTransaction();
    	db.update(io);
    	db.update(selectedd);
    	db.commitTransaction();
    	AppInitInfo.showMessage("详单修改", "处理成功");
    }
    
    public void onRowCancel(RowEditEvent event) {
    	//AppInitInfo.showMessage("取消修改", "处理成功");
    }
    
    //计算金额字段
    public BigDecimal calculateAmount() {
    	BigDecimal bd = new BigDecimal(0);
    	for(BmePayrollDetail bse:vod) {    		
    		bd = bd.add(bse.getAmount());    		
    	}
    	return bd;
    }
    
	public BmePayroll getIo() {
		return io;
	}

	public void setIo(BmePayroll io) {
		this.io = io;
	}

	public List<BmePayrollDetail> getVod() {
		return vod;
	}

	public void setVod(List<BmePayrollDetail> vod) {
		this.vod = vod;
	}

	public BmePayrollDetail getSelectedd() {
		return selectedd;
	}

	public void setSelectedd(BmePayrollDetail selectedd) {
		this.selectedd = selectedd;
	}

	public String getUploadedFile() {
		return uploadedFile;
	}

	public void setUploadedFile(String uploadedFile) {
		this.uploadedFile = uploadedFile;
	}

	public String getUploadedFileImage() {
		return uploadedFileImage;
	}

	public void setUploadedFileImage(String uploadedFileImage) {
		this.uploadedFileImage = uploadedFileImage;
	}

	public BmeContract getSelectedContract() {
		return selectedContract;
	}

	public void setSelectedContract(BmeContract selectedContract) {
		this.selectedContract = selectedContract;
	}

	public List<BmeContract> getBmeContracts() {
		return bmeContracts;
	}

	public void setBmeContracts(List<BmeContract> bmeContracts) {
		this.bmeContracts = bmeContracts;
	}

	public String getUploadForType() {
		return uploadForType;
	}

	public void setUploadForType(String uploadForType) {
		this.uploadForType = uploadForType;
	}

	public String getUploadForId() {
		return uploadForId;
	}

	public void setUploadForId(String uploadForId) {
		this.uploadForId = uploadForId;
	}

	public String getUploadForName() {
		return uploadForName;
	}

	public void setUploadForName(String uploadForName) {
		this.uploadForName = uploadForName;
	}

	public List<BmeAcceptionDetail> getBmeAcceptionDetails() {
		return bmeAcceptionDetails;
	}

	public void setBmeAcceptionDetails(List<BmeAcceptionDetail> bmeAcceptionDetails) {
		this.bmeAcceptionDetails = bmeAcceptionDetails;
	}

	public BmeAcceptionDetail getSelectedAcceptionDetail() {
		return selectedAcceptionDetail;
	}

	public void setSelectedAcceptionDetail(BmeAcceptionDetail selectedAcceptionDetail) {
		this.selectedAcceptionDetail = selectedAcceptionDetail;
	}

	public List<BmeAcceptionDetail> getSelectedAcceptionDetails() {
		return selectedAcceptionDetails;
	}

	public void setSelectedAcceptionDetails(List<BmeAcceptionDetail> selectedAcceptionDetails) {
		this.selectedAcceptionDetails = selectedAcceptionDetails;
	}

	public List<SelectItem> getItemsStatus() {
		return itemsStatus;
	}

	public void setItemsStatus(List<SelectItem> itemsStatus) {
		this.itemsStatus = itemsStatus;
	}
	
}